import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import authApi from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
    // 状态
    const user = ref(null)
    const token = ref(null)
    const isAuthenticated = ref(false)

    // 计算属性
    const userRole = computed(() => user.value?.role)
    const isAdmin = computed(() => userRole.value === 'ADMIN')
    const isTeacher = computed(() => userRole.value === 'TEACHER')
    const isStudent = computed(() => userRole.value === 'STUDENT')

    // 从本地存储恢复状态
    const initAuth = () => {
        const savedToken = localStorage.getItem('auth_token')
        const savedUser = localStorage.getItem('auth_user')

        if (savedToken && savedUser) {
            token.value = savedToken
            user.value = JSON.parse(savedUser)
            isAuthenticated.value = true
        }
    }

    // 登录
    const login = async (payload) => {
        user.value = payload.user
        token.value = payload.token
        isAuthenticated.value = true

        // 保存到本地存储
        localStorage.setItem('auth_token', payload.token)
        localStorage.setItem('auth_user', JSON.stringify(payload.user))
    }

    // 登出
    const logout = async () => {
        try {
            await authApi.logout()
        } catch (error) {
            console.error('登出API调用失败:', error)
        } finally {
            // 清除状态
            user.value = null
            token.value = null
            isAuthenticated.value = false

            // 清除本地存储
            localStorage.removeItem('auth_token')
            localStorage.removeItem('auth_user')
        }
    }

    // 获取当前用户信息
    const fetchCurrentUser = async () => {
        try {
            const response = await authApi.getCurrentUser()
            user.value = response.data
            return response.data
        } catch (error) {
            console.error('获取用户信息失败:', error)
            throw error
        }
    }

    // 初始化
    initAuth()

    return {
        // 状态
        user,
        token,
        isAuthenticated,

        // 计算属性
        userRole,
        isAdmin,
        isTeacher,
        isStudent,

        // 方法
        login,
        logout,
        fetchCurrentUser,
        initAuth
    }
})
